# 导入相关库和模块
from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from database import SessionLocal
import sys
from api.base_controller import BaseController
from config.logging import logger
from services.api.red_book_user_api_service import RedBookUserApiService


# 定义获取数据库会话的依赖
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 定义控制器类
class RedBookUserApi(BaseController):
    def __init__(self):
        super().__init__()
        self.router = APIRouter()

    async def create_user(self, userInfo: dict, db: Session = Depends(get_db)):
        """
        Create a new user in the red_book_users
        userInfo: name password
        """
        services = RedBookUserApiService(db)
        result = await services.create_user(userInfo)
        if isinstance(result, dict) and "error" in result:
            return self.failure_response(status_code=400, message=result["error"])
        return self.success_response(data=result, message="success")

    async def user_login(self, userInfo: dict, db: Session = Depends(get_db)):
        """
        Create a new user in the red_book_users
        userInfo: name password
        """
        services = RedBookUserApiService(db)
        result = await services.user_login(userInfo)
        if isinstance(result, dict) and "error" in result:
            return self.failure_response(status_code=400, message=result["error"])
        return self.success_response(data=result, message="success")

    async def user_info(self, request: Request):
        """
        用户信息
        :param request:
        :return:
        """
        result = request.state.user

        if result['avatar_url']:
            image_url = result['avatar_url'].lstrip('/')
            result['avatar_url'] = '{}{}'.format(request.base_url, image_url)
        else:
            result['avatar_url'] = None
        print(f"--------{result}-----------")
        return self.success_response(data=result, message="success")


# 使用
red_book_user_api = RedBookUserApi()
router = red_book_user_api.router
